package com.lhl.jwt.security.providers;

import com.lhl.jwt.service.JwtUserDetailsService;
import com.lhl.jwt.token.JwtAuthenticationToken;
import com.lhl.jwt.token.WxAuthenticationToken;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

/**
 * @className: com.lhl.jwt.security.providers.WxAppletAuthenticationProvider
 * @description: 微信登入验证
 * @author: king
 * @date: 2020-12-22 15:01
 **/
@Api(tags = "WxAppletAuthenticationProvider", produces = "WxAppletAuthenticationProvider")
@Slf4j
public class WxAuthenticationProvider implements AuthenticationProvider, InitializingBean {

    private final JwtUserDetailsService userDetailsService;

    public WxAuthenticationProvider(JwtUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
    }
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(WxAuthenticationToken.class, authentication, () -> {
            return "Only WxAppletAuthenticationToken is supported";
        });
        WxAuthenticationToken  wxAuthenticationToken = (WxAuthenticationToken) authentication;
        UserDetails userDetails = null;
        //企业微信
        if("cp".equals(wxAuthenticationToken.getType())){
//            userDetails = userDetailsService.loadUserByUserId(wxAuthenticationToken.getWxId());
            userDetails = userDetailsService.loadUserByMobile(wxAuthenticationToken.getMobile());
        }else if("mp".equals(wxAuthenticationToken.getType()) || "miniApp".equals(wxAuthenticationToken.getType())){
            userDetails = userDetailsService.loadUserByOpenId(wxAuthenticationToken.getWxId());
        }
        JwtAuthenticationToken token = new JwtAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        return token;
    }

    /**
     * @param: authentication
     * @description: 判断只有传入WxAppletAuthenticationToken的时候才使用这个Provider
     * supports会在AuthenticationManager层被调用
     * @return: boolean
     * @author: king
     * @date: 2020-12-22 17:13
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(WxAuthenticationToken.class);
    }
}
